import nProgress from 'nprogress'
import router, { asyncRoutes, constantRoutes } from './router'
import store from './store'
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  nProgress.start()// 开启进度条
  // next是一个必须执行的钩子函数 不执行就卡住了
  const token = store.getters.token
  if (token) {
    if (to.path === '/login') {
      next('/')
      // 关闭进度条
      nProgress.done()
    } else {
      // 1.判断是否获取过资料 userInfo.userId
      // 2.如果没有，派发vueX仓库中action事件
      if (!store.getters.userId) {
        // roles-角色信息
        const { roles } = await store.dispatch('user/updateUserinfoSync')
        console.log(roles)
        // console.log(asyncRoutes) //所有动态路由信息
        // 筛选动态路由-根据角色进行筛选
        const filterRouters = asyncRoutes.filter(item => {
          return roles.menus.includes(item.name)
        })
        // 添加到路由表
        router.addRoutes([...filterRouters, { path: '*', redirect: '/404', hidden: true }])
        // constantRoutes 静态路由   动态路由 filterRouters
        store.commit('user/setRoutes', [...constantRoutes, ...filterRouters])
        console.log(filterRouters)
        // 路由的以知缺陷
        // 添加动态路由之后 需要转发一下
        // next(to.path)--拥有路由信息
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    // 判断白名单
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      // 关闭进度条
      nProgress.done()
    }
  }
})
router.afterEach(() => {
  // 关闭进度条
  nProgress.done()
})
